package com.aaa.mysecurity.filter;

import cn.hutool.json.JSONUtil;
import com.aaa.mysecurity.util.JwtUtil;
import com.aaa.mysecurity.util.Result;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ：ludi（206913808@qq.com）
 * @date ：Created in 2022/11/3 14:51
 * @description：
 * @modified By：
 * @version:
 */
@Component
public class MyFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        response.setContentType("application/JSON;charset=utf-8");
        /**
         * 获取请求路径和请求方式
         */
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        /**
         * 释放登录
         */
        if ("POST".equals(method) && "/login".equals(requestURI)) {
            filterChain.doFilter(request, response);
            return;
        }
        /**
         * 获取请求头的token
         */
        String token = request.getHeader("token");
        /**
         * 判断是否携带token值
         */
        if (StringUtils.hasText(token)) {
            /**
             * 检验是否有效
             */
            boolean b = JwtUtil.verifyToken(token);
            if (b) {
                /**
                 * 解析token内容
                 */
                Map<String, Object> map = JwtUtil.getTokenChaim(token);
                String username = map.get("username").toString();
                List<String> list = (List<String>) map.get("authorities");
                /**
                 * 把解析的结果封装到SecurtitContext中，可以交于security判断相应的权限
                 */
                List<SimpleGrantedAuthority> authorities = list.stream().map(item -> new SimpleGrantedAuthority(item)).collect(Collectors.toList());
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, null, authorities);
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                filterChain.doFilter(request, response);
                return;
            }
        }
        /**
         * token为null或者token无效时。响应一个json数据.
         */
        PrintWriter writer = response.getWriter();
        Result result = new Result(500, "token无效", null);
        String jsonStr = JSONUtil.toJsonStr(result);
        writer.print(jsonStr);
        writer.flush();
        writer.close();
    }
}